package cn.klaw.config;

import cn.hutool.http.useragent.*;
import cn.klaw.i18n.config.I18nProperties;
import cn.klaw.properties.GatewayWhite;
import cn.klaw.properties.MvcSecurityProperties;
import cn.klaw.properties.SecurityProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration(proxyBeanMethods = false)
public class CoreAutoConfiguration implements InitializingBean {


    @Bean
    @ConditionalOnMissingBean
    @ConfigurationProperties(prefix = GatewayWhite.PREFIX)
    public GatewayWhite getGateWhite(){
        return new GatewayWhite();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConfigurationProperties(prefix = SecurityProperties.PREFIX)
    public SecurityProperties getSecurityProperties(){
        return new SecurityProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConfigurationProperties(prefix = ConfigValueUtil.PREFIX)
    public ConfigValueUtil getConfigValueUtil(){
        return new ConfigValueUtil();
    }

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.messages")
    public I18nProperties getI18nProperties(){
        return new I18nProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConfigurationProperties(prefix = MvcSecurityProperties.PREFIX)
    public MvcSecurityProperties getCorsProperties(){
        return new MvcSecurityProperties();
    }

    @Bean
    public ApplicationStartErrorCheck getApplicationStartupErrorCheck(){
        return new ApplicationStartErrorCheck();
    }

    @Override
    public void afterPropertiesSet() {
        // UserAgent
        initUserAgent();
    }

    private void initUserAgent(){
        // Harmony 鸿蒙OS
        OS.addCustomOs("OpenHarmony", "OpenHarmony", "OpenHarmony\\s+(\\d+([._]\\d+)*)");
        // 鸿蒙OS移动端
        Platform platform = new Platform("OpenHarmony", "Phone;\\s*OpenHarmony\\s*");
        Platform.mobilePlatforms.add(platform);
        Platform.platforms.add(platform);
        Browser.browers.add(0, new Browser("OpenHarmony", "Phone;\\s*OpenHarmony.*ArkWeb", "ArkWeb\\/([\\d\\w\\.\\-]+)"));
    }
}
